package com.practice.backend.Controller;

import com.practice.backend.Common.Jwt;
import com.practice.backend.Common.Result;
import com.practice.backend.Entity.*;
import com.practice.backend.Repository.GoodsRepository;
import com.practice.backend.Repository.LoginHistoryRepository;
import com.practice.backend.Repository.OrderRepository;
import com.practice.backend.Repository.WarehouseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/warehouse")
public class WarehouseController {
    @Autowired
    private WarehouseRepository warehouseRepository;
    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private LoginHistoryRepository loginHistoryRepository;


    @RequestMapping("/findAll")
    public Result findAll() {
        return Result.success(true, "查询成功", warehouseRepository.findAll().size(), warehouseRepository.findAll());
    }

    @RequestMapping("/findGoodsById")
    public Result findGoodsById(@Param("id") int id) {
        List<Goods> byWareHouseId = goodsRepository.findByWareHouseId(id);
        return Result.success(true, "查询成功", byWareHouseId.size(), byWareHouseId);
    }

    @PutMapping("/transfer")
    @Transactional
    public Result transfer(@RequestBody TransRequest request) {
        Order order = new Order();
        Integer fromWarehouseId = request.getFromWarehouseId();
        Integer goodsId = request.getGoodsId();
        List<TransferRow> transferRows = request.getTransferRows();

        // 1. 计算总划拨数量
        int totalTransferNum = transferRows.stream().mapToInt(TransferRow::getNum).sum();
        if (totalTransferNum <= 0) {
            return Result.error(false, "划拨数量必须大于0", 0, null);
        }

        // 2. 获取并锁定出发仓库货物（使用悲观锁）
        Goods fromGoods = goodsRepository.findById(goodsId)
                .orElse(null);
        if (fromGoods == null || !fromGoods.getWareHouseId().equals(fromWarehouseId)) {
            return Result.error(false, "出发仓库货物不存在", 0, null);
        }

        // 3. 验证库存数量
        if (fromGoods.getCount() < totalTransferNum) {
            return Result.error(false, "库存数量不足", 0, null);
        }

        // 4. 处理每个目标仓库
        for (TransferRow row : transferRows) {
            Integer targetWarehouse = row.getTargetWarehouse();
            Integer num = row.getNum();

            // 4.1 查找目标仓库相同属性的货物
            List<Goods> targetGoodsList = goodsRepository.findByWareHouseId(targetWarehouse);
            Goods targetGoods = null;
            for (Goods goods : targetGoodsList) {
                if (goods.getName().equals(fromGoods.getName()) &&
                        Objects.equals(goods.getWeight(), fromGoods.getWeight()) &&
                        Objects.equals(goods.getVolume(), fromGoods.getVolume()) &&
                        Objects.equals(goods.getQuality(), fromGoods.getQuality())) {
                    targetGoods = goods;
                    break;
                }
            }

            // 4.2 更新或创建目标仓库记录
            if (targetGoods != null) {
                targetGoods.setCount(targetGoods.getCount() + num);
                goodsRepository.save(targetGoods);
            } else {
                Goods newGoods = new Goods();
                newGoods.setName(fromGoods.getName());
                newGoods.setWeight(fromGoods.getWeight());
                newGoods.setVolume(fromGoods.getVolume());
                newGoods.setQuality(fromGoods.getQuality());
                newGoods.setCount(num);
                newGoods.setWareHouseId(targetWarehouse);
                goodsRepository.save(newGoods);
            }
            //增加划拨订单

            order.setGoodsId(goodsId);
            order.setCost(0);
            order.setWareHouseId(fromWarehouseId); // 源仓库
            order.setType("划拨");
            order.setCustomerName("---");
            order.setCustomerPhone("---");
            order.setDealCount(num);
            order.setDealTime(LocalDateTime.now());
            order.setDealPurpose("---");
            order.setGoodsQuality(goodsRepository.findQualityById(goodsId));
            //当前登陆的用户的id
            List<LoginHistory> all = loginHistoryRepository.findAll();
            System.out.println( all);
            //获取最后一条记录
            order.setUserId(Jwt.parseToken(all.get(all.size()-1).getToken()));
            System.out.println( order);
        }


        orderRepository.save(order);
        // 5. 更新出发仓库库存
        fromGoods.setCount(fromGoods.getCount() - totalTransferNum);
        goodsRepository.save(fromGoods);


        return Result.success(true, "划拨成功", 0, null);
    }
}
